/**************************************************************************(C)*
 *
 *  This file is part of the GreenHills project
 *  Copyright (C) 2009  Tieto Corporation
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  Not for commmercial use. Only with Tieto permission.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************(C)*/


#include "../event.h"
#include "util/binstream.h"
#include "util/memstreambuf.h"

#include <assert.h>

using namespace greenhills::event;
using namespace greenhills::util;
using namespace std;

CEvent::CEvent()
{
}

CEvent::~CEvent()
{
}

obinstream &CEvent::operator<<(obinstream &pStream) const
{
    return pStream;
}

ibinstream &CEvent::operator>>(ibinstream &pStream)
{
    return pStream;
}

CEvent *CEvent::deserialize(ibinstream &pStream)
{
    unsigned int type;
    pStream >> type;

    CEvent *event = CEventFactory::instance()
                    .buildEvent((CEvent::eEventType)type);
    if (event != 0)
        event->operator >>(pStream);

    return event;
}

void CEvent::serialize(const CEvent *event, obinstream &pStream)
{
    assert(event != 0);

    unsigned int type = event->type();
    pStream << type;

    event->operator <<(pStream);
}

CEventFactory::CEventFactory()
{
}

void CEventFactory::registerBuilder(IEventBuilder* builder)
{
    builders.push_back(builder);
}

CEvent* CEventFactory::buildEvent(CEvent::eEventType type)
{
    for (vector<IEventBuilder*>::iterator it = builders.begin();
            it!=builders.end(); ++it)
    {
        if ((*it)->type() == type)
            return (*it)->build();
    }
    return 0;
}
